package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.*;
import com.lei.springbootpractice.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private ProductsService productsService;

    @Autowired
    private UserService userService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CartService cartService;

    @Autowired
    private OrdersService ordersService;


    
    @Autowired
    private ConsoleService consoleService;
    
    @Autowired
    private ConversationService conversationService;
    
    @Autowired
    private NotificationService notificationService;

    @GetMapping("/dashboard")
    public String dashboard(HttpSession session, Model model) {
        String userID = (String) session.getAttribute("loggedInUser");
        UserPojo user = userService.getUserByUserID(userID);
        
        // 进入用户工作台时刷新分类缓存
        categoryService.clearCache();
        categoryService.warmUpCache();
        
        model.addAttribute("username", user.getUserName());
        model.addAttribute("userRole", user.getRole());
        model.addAttribute("isAdmin", false);  // 普通用户不是管理员
        
        return "customer/dashboard";
    }

    @GetMapping("/categories")
    public String categories(Model model) {
        List<CategoryPojo> categories = categoryService.getAllCategories();
        model.addAttribute("categories", categories);
        return "customer/categories";
    }

    @GetMapping("/products")
    public String products(@RequestParam(value = "categoryId", required = false) String categoryId,
                          @RequestParam(value = "parentCategoryId", required = false) String parentCategoryId,
                          @RequestParam(value = "minPrice", required = false) Double minPrice,
                          @RequestParam(value = "maxPrice", required = false) Double maxPrice,
                          Model model) {
        
        // 获取所有父分类
        List<CategoryPojo> parentCategories = categoryService.getParentCategories();
        model.addAttribute("parentCategories", parentCategories);

        // 构建子分类映射
        Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
        for (CategoryPojo parent : parentCategories) {
            List<CategoryPojo> subCategories = categoryService.getSubcategories(parent.getCategoryId());
            subCategoriesMap.put(parent.getCategoryId(), subCategories);
        }
        model.addAttribute("subCategoriesMap", subCategoriesMap);

        // 传递选中的分类状态
        model.addAttribute("selectedCategory", categoryId);
        model.addAttribute("selectedParentCategory", parentCategoryId);

        // 构建筛选条件
        List<String> categoryIds = new ArrayList<>();
        if (categoryId != null && !categoryId.isEmpty()) {
            categoryIds.add(categoryId);
        } else if (parentCategoryId != null && !parentCategoryId.isEmpty()) {
            // 如果只选择了父分类，获取该父分类下的所有子分类
            List<CategoryPojo> subCategories = categoryService.getSubcategories(parentCategoryId);
            for (CategoryPojo sub : subCategories) {
                categoryIds.add(sub.getCategoryId());
            }
        }

        // 获取筛选后的商品
        List<ProductsPojo> products = productsService.getProductsByFilter(categoryIds, minPrice, maxPrice);
        model.addAttribute("products", products);

        return "customer/product-list";
    }


    @GetMapping("/products/{id}")
    public String viewProduct(@PathVariable("id") String productId, Model model) {
        ProductsPojo product = productsService.getProductById(productId);
        model.addAttribute("product", product);
        return "customer/product-detail";
    }

    @GetMapping("/under-construction")
    public String underConstruction() {
        return "customer/under-construction";
    }

    @GetMapping("/cart")
    public String viewCart(HttpSession session, Model model) {
        String userId = (String) session.getAttribute("loggedInUser");
        if (userId == null) {
            return "redirect:/login";
        }
        UserPojo user = userService.getUserByUserID(userId);
        List<CartPojo> cartItems = cartService.getCartByUserId(userId);
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("username", user.getUserName());
        return "customer/cart";
    }

    @GetMapping("/orders")
    public String myOrders(HttpSession session, Model model) {
        String userId = (String) session.getAttribute("loggedInUser");
        List<OrdersPojo> orders = ordersService.getOrdersByUserId(userId);
        model.addAttribute("orders", orders);
        return "customer/orders";
    }

    @GetMapping("/wishlist")
    public String wishlist() {
        return "customer/under-construction";
    }

    @GetMapping("/profile")
    public String profile() {
        return "customer/under-construction";
    }
    
    @GetMapping("/customer-service")
    public String customerService(HttpSession session, Model model) {
        String userId = (String) session.getAttribute("loggedInUser");
        if (userId == null) {
            return "redirect:/login";
        }
        
        UserPojo user = userService.getUserByUserID(userId);
        model.addAttribute("username", user.getUserName());
        model.addAttribute("userRole", user.getRole());
        
        // 获取所有客服列表
        List<UserPojo> customerServices = userService.getCustomerServices();
        System.out.println("=== 客服列表调试信息 ===");
        System.out.println("客服列表大小: " + (customerServices != null ? customerServices.size() : "null"));
        if (customerServices != null) {
            for (UserPojo service : customerServices) {
                System.out.println("客服: ID=" + service.getUserID() + ", 姓名=" + service.getUserName() + ", 角色=" + service.getRole());
            }
        }
        System.out.println("=== 调试信息结束 ===");
        model.addAttribute("customerServices", customerServices);
        
        // 获取当前活跃对话
        try {
            ConversationPojo activeConversation = conversationService.getActiveConversationByCustomer(userId);
            if (activeConversation != null) {
                // 获取对话记录
                List<ConsolePojo> messages = consoleService.getConversationMessages(activeConversation.getConversationId());
                UserPojo currentService = userService.getUserByUserID(activeConversation.getCustomerServiceId());
                
                model.addAttribute("messages", messages);
                model.addAttribute("hasConversation", true);
                model.addAttribute("currentConversation", activeConversation);
                model.addAttribute("currentService", currentService);
            } else {
                model.addAttribute("messages", java.util.Collections.emptyList());
                model.addAttribute("hasConversation", false);
            }
        } catch (Exception e) {
            model.addAttribute("messages", java.util.Collections.emptyList());
            model.addAttribute("hasConversation", false);
            model.addAttribute("error", "获取对话记录失败：" + e.getMessage());
        }
        
        return "customer/customer-service";
    }
    
    @PostMapping("/start-conversation")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> startConversation(@RequestBody Map<String, String> request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userId);
            if (user == null || !"customer".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            String customerServiceId = request.get("customerServiceId");
            
            if (customerServiceId == null || customerServiceId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择客服");
                return ResponseEntity.ok(response);
            }
            
            // 验证客服是否存在
            UserPojo customerService = userService.getUserByUserID(customerServiceId);
            if (customerService == null || !"customer_service".equals(customerService.getRole())) {
                response.put("success", false);
                response.put("message", "选择的客服不存在");
                return ResponseEntity.ok(response);
            }
            
            // 开始与指定客服的对话
            ConversationPojo conversation = conversationService.startConversationWithSpecificService(userId, customerServiceId);
            
            response.put("success", true);
            response.put("message", "已连接到客服 " + customerService.getUserName());
            response.put("conversationId", conversation.getConversationId());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "连接失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/get-messages")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getMessages(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            // 获取当前活跃对话
            ConversationPojo activeConversation = conversationService.getActiveConversationByCustomer(userId);
            if (activeConversation != null) {
                // 获取对话记录
                List<ConsolePojo> messages = consoleService.getConversationMessages(activeConversation.getConversationId());
                
                // 为每条消息添加发送者信息
                List<Map<String, Object>> messageList = new ArrayList<>();
                for (ConsolePojo message : messages) {
                    Map<String, Object> msgData = new HashMap<>();
                    UserPojo sender = userService.getUserByUserID(message.getSenderId());
                    
                    msgData.put("content", message.getContent());
                    msgData.put("createTime", message.getCreateTime());
                    msgData.put("senderName", sender.getUserName());
                    msgData.put("isFromCustomer", userId.equals(message.getSenderId()));
                    
                    messageList.add(msgData);
                }
                
                response.put("success", true);
                response.put("messages", messageList);
                response.put("hasConversation", true);
            } else {
                response.put("success", true);
                response.put("messages", new ArrayList<>());
                response.put("hasConversation", false);
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取消息失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/send-to-customer-service")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> sendToCustomerService(@RequestBody Map<String, String> request, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userId);
            if (user == null || !"customer".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            String message = request.get("message");
            
            if (message == null || message.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "消息内容不能为空");
                return ResponseEntity.ok(response);
            }
            
            boolean success = consoleService.sendMessageFromCustomer(userId, message.trim());
            
            if (success) {
                response.put("success", true);
                response.put("message", "消息发送成功");
                
                // 返回最新的消息列表
                ConversationPojo activeConversation = conversationService.getActiveConversationByCustomer(userId);
                if (activeConversation != null) {
                    List<ConsolePojo> messages = consoleService.getConversationMessages(activeConversation.getConversationId());
                    List<Map<String, Object>> messageList = new ArrayList<>();
                    for (ConsolePojo msg : messages) {
                        Map<String, Object> msgData = new HashMap<>();
                        UserPojo sender = userService.getUserByUserID(msg.getSenderId());
                        
                        msgData.put("content", msg.getContent());
                        msgData.put("createTime", msg.getCreateTime());
                        msgData.put("senderName", sender.getUserName());
                        msgData.put("isFromCustomer", userId.equals(msg.getSenderId()));
                        
                        messageList.add(msgData);
                    }
                    response.put("messages", messageList);
                }
            } else {
                response.put("success", false);
                response.put("message", "暂无客服在线，请稍后再试");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "发送失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/close-conversation")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> closeConversation(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            UserPojo user = userService.getUserByUserID(userId);
            if (user == null || !"customer".equals(user.getRole())) {
                response.put("success", false);
                response.put("message", "权限不足");
                return ResponseEntity.ok(response);
            }
            
            // 获取当前活跃对话
            ConversationPojo activeConversation = conversationService.getActiveConversationByCustomer(userId);
            if (activeConversation != null) {
                // 结束对话
                conversationService.closeConversation(activeConversation.getConversationId());
                response.put("success", true);
                response.put("message", "对话已结束");
            } else {
                response.put("success", false);
                response.put("message", "没有活跃的对话");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "结束对话失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/mark-messages-read")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> markMessagesRead(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            // 使用新的通知系统标记消息为已读
            boolean success = notificationService.markMessageNotificationsAsRead(userId);
            
            // 同时保持原有的对话未读计数清零逻辑
            ConversationPojo activeConversation = conversationService.getActiveConversationByCustomer(userId);
            if (activeConversation != null) {
                conversationService.clearUnreadCount(activeConversation.getConversationId(), true);
            }
            
            response.put("success", success);
            if (!success) {
                response.put("message", "标记已读失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "标记已读失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/unread-count")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getUnreadCount(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            // 使用新的通知系统获取未读消息数
            int unreadCount = notificationService.getMessageUnreadCount(userId);
            response.put("success", true);
            response.put("unreadCount", unreadCount);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取未读消息数失败：" + e.getMessage());
            response.put("unreadCount", 0);
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/notifications")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getNotifications(HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String userId = (String) session.getAttribute("loggedInUser");
            if (userId == null) {
                response.put("success", false);
                response.put("message", "请重新登录");
                return ResponseEntity.ok(response);
            }
            
            // 获取最新的通知列表
            List<NotificationStatusPojo> notifications = notificationService.getUnreadNotifications(userId, 10);
            response.put("success", true);
            response.put("notifications", notifications);
            response.put("unreadCount", notifications.size());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取通知失败：" + e.getMessage());
            response.put("notifications", new ArrayList<>());
        }
        
        return ResponseEntity.ok(response);
    }
}
